package com.example.gobang.game;

import com.example.gobang.model.User;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

// 房间管理器类.
// 这个类也希望有唯一实例.
@Component
public class RoomManager {
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    //连接房间和用户
    private ConcurrentHashMap<Integer, String> userRoomId = new ConcurrentHashMap<>();


    public void add(Room room,int userId1,int userId2) {
        rooms.put(room.getRoomId(), room);
        userRoomId.put(userId1,room.getRoomId());
        userRoomId.put(userId2,room.getRoomId());

    }

    public void remove(String roomId,int userId1,int userId2) {
        rooms.remove(roomId);
        userRoomId.remove(userId1);
        userRoomId.remove(userId2);
    }

    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(Integer userId) {
        String roomId = userRoomId.get(userId);
        if (roomId == null) {
            // userId -> roomId 映射关系不存在, 直接返回 null
            return null;
        }
        return rooms.get(roomId);
    }
}
